var availableSignature;
var configPanelIsOpen = false;
var conflictPanelIsOpen = false;
var currentPlannificationId = 0;
var dp;
var periods = null;
var defaultPeriod;
var reservConflictDict={};
var proccesor;
var strYear={1:"1ro",2:"2do",3:"3ro",4:"4to",5:"5to",6:"6to",7:"7mo",8:"8vo",9:"9no",10:"10mo"};
var iAmIn = null;
var viewPlanningRecived = false;
var plannIsOpen = false;


function getStrYear(key){
	return strYear[key];
}

daysOfWeek={ 
	     1:"Lunes", 
	     2:"Martes", 
	     3:"Mi\u00E9rcoles",
	     4:"Jueves",
	     5:"Viernes",
	     6:"S\u00E1bado"
	};

function setDefaultPeriod(period){
	defaultPeriod=period;
}

function getDefaultPeriod(){
	return defaultPeriod;
}

function newPlanification(flag) {
	if (flag) {
		getPeriods();
		$("#selectPlanification").hide("clip", {}, 1000);
		$("#planningFilters").hide("clip", {}, 1000);
		$("#selectCareerAndYear").show("clip", {}, 1000);
		$("#addStartPeriod").datepicker();
		$("#addFinishPeriod").datepicker();
	} else {
		$("#selectCareerAndYear").hide("clip", {}, 1000);
		$("#selectPlanification").show("clip", {}, 1000);
		$("#planningFilters").show("clip", {}, 1000);
		$("#contentHistoryPlanifications").hide();
		$("#historyCareerAndYear").show();
		$("#loadHistoryCareerAndYear").hide();
	}
	cleanInputsCareerAndyear();
	initReservInConflict();
}

function getSendedPlanifiaction() {
	var currentDiv = $("#contentPlanificationsRecived");
	var table = "";
	var tr = "";
	currentDiv.html('');
	
	Number.prototype.padLeft = function(base,chr){
		   var  len = (String(base || 10).length - String(this).length)+1;
		   return len > 0? new Array(len).join(chr || '0')+this : this;
		};
	
	table+="<table class='table table-hover'><thead><tr><th>Carrera</th><th>A\u00F1o</th><th>Autor</th><th>Per\u00EDodo</th><th>Modificada</th><th>Enviada</th><th>Estado</th><th></th></tr></thead><tbody>";
	
	//sperez: Aca deber�a ir el m�todo de pablo
	$.getJSON('/enma/planning/getSended/', function(data) {
			if(data.responseCode == 200){
				clearPlanningsRepo();
				for(var i = 0; i<data.planningsDTO.length; i++){
					var auxDiv = data.planningsDTO[i];
					period=auxDiv.periodDTO['startDate']+' - '+auxDiv.periodDTO['endDate'];
					getPlanningsRepo()[auxDiv.planningId]=auxDiv;
					tr += "<tr><td>"+auxDiv.career+"</td><td>"+auxDiv.year+"</td><td>"+auxDiv.userName+"</td><td>"+period+"</td><td>"+auxDiv.lastModDate+"</td><td>"+auxDiv.sendDate+"</td><td>"+auxDiv.status+"</td><td><input type='radio' name='radioListItemRecived' value='"+auxDiv.planningId+"'></td></tr>";
					}
				table += tr + "</tbody></table>";
	            currentDiv.append(table);
			}
			setTimeout(function() { 
				hideProgress('loadPlann');	    
		    }, 1000);
			
		});

	
	viewPlanningRecived = true;
	$("#sendedPlanifiactionbutton").hide();
	$("#deletePlanification").hide();
	$("#unConfirmPlanification").hide();
	$("#newPlanificacion").hide();
	$("#planningFilters").hide();
	$("#closePlanifiactionbutton").show();
	$("#unlockPlanifiactionbutton").show();
	$("#panelBlockPlanning").show();
	$("#contentPlanificationsRecived").show("puff", {}, 1000);
}

function closeSendedPlanifiaction(){
	viewPlanningRecived = false;
	$("#closePlanifiactionbutton").hide();
	$("#unlockPlanifiactionbutton").hide();
	$("#panelBlockPlanning").hide();
	$("#contentPlanificationsRecived").hide("puff", {}, 1000);
	$("#sendedPlanifiactionbutton").show();
	$("#deletePlanification").show();
	$("#unConfirmPlanification").show();
	$("#newPlanificacion").show();
	initPlanning();
}

function unlockSendedPlanifiaction(){
	$("#unlockSendedPlanifiactionDialog").dialog();
}

function unlockSendedPlanifiactionPhaseTwo() {
	
	var selected = $("input[type='radio'][name='radioListItemRecived']:checked");
	if (selected.length > 0){
		var pID = selected.val();
		postJSON("/enma/planning/unlock/",pID, function(data) {
			if(data.responseCode == 200){
				showProgress('loadPlann');
				getSendedPlanifiaction();
			}else{
				$("#errorUnlockPlanificationDialog").dialog();
			}	
		});
	} else {
		$("#selectUnlockPlanificationDialog").dialog();
	}
	$("#unlockSendedPlanifiactionDialog").dialog("close");
}

function closeHistory(){
	$("#closeHistorybutton").hide();
	$("#contentHistoryPlanifications").hide("puff", {}, 1000);
	$("#confirmCareerAndYear").show();
	$("#loadHistoryCareerAndYear").hide();
	$("#historyCareerAndYear").show();
	
}

function setDataProcessor(value,id){
	proccesor=value;
}

function getDataProcessor(){
	return proccesor;
}

function openPlanification() {
	var selected = null;
	if (viewPlanningRecived){
		selected = $("input[type='radio'][name='radioListItemRecived']:checked");
	}else{
		selected = $("input[type='radio'][name='radioListItem']:checked");
	}
	if (selected.length > 0){
		$("#selectPlanification").hide("fold", {}, 1000);
		currentPlannificationId = selected.val();
		initReservInConflict();
		goToPlanning(parseInt(currentPlannificationId),getDataProcessor());
		plannIsOpen = true;
	} else {
		$("#selectOpenPlanificationDialog").dialog();
		plannIsOpen = false;
	}
}

function deletePlanification() {
	$("#deletePlanificationDialog").dialog();
}

function unConfirmPlanification(){
	$("#unConfirmPlanificationDialog").dialog();
}

function deletePlanificationPhaseTwo() {
	var selected = $("input[type='radio'][name='radioListItem']:checked");
	if (selected.length > 0){
		
		//sperez: servicio para eliminar planificaci�n.
		var pID = selected.val();
		postJSON("/enma/planning/delete/",pID, function(data) {
			if(data.responseCode == 200){
				//sperez: si lo elimina bien llamar a esto.
				doPlanningFilter();
			}else{
				$("#errorDeletePlanificationDialog").dialog();
			}	
		});
	} else {
		$("#selectDeletePlanificationDialog").dialog();
	}
	$("#deletePlanificationDialog").dialog("close");
}

function unConfirmPlanificationPhaseTwo() {
	var selected = $("input[type='radio'][name='radioListItem']:checked");
	if (selected.length > 0){
		
		var pID = selected.val();
		postJSON("/enma/planning/unConfirm/",pID, function(data) {
			if(data.responseCode == 200){
				doPlanningFilter();
			}else{
				alert(data.message);
			}	
		});
	} else {
		$("#selectUnConfirmPlanificationDialog").dialog();
	}
	$("#unConfirmPlanificationDialog").dialog("close");
}

var planificationsConflicts = [];

function getReservConflictDict(){
	return reservConflictDict;
}

function updateDictionary(reserv){
	deleteOnUpdateReservInConlfict(reserv.id,reserv.conflictsResDTO);
	reservConflictDict[reserv.id]=prepareReservConflicts(reserv);
	updateReservWhereIam(reserv);
}

function updateReservWhereIam(reserv){
    for(var key in reservConflictDict){
        
        if(reservConflictDict[key][reserv.id]){
            var whereIAm=scheduler._events[key];
            var sDate = new Date(whereIAm.start_date),startDate=[sDate.getHours().padLeft(),sDate.getMinutes().padLeft()].join(':');
    		var eDate = new Date(whereIAm.end_date),endDate=[eDate.getHours().padLeft(),eDate.getMinutes().padLeft()].join(':');
    		var group=(whereIAm.group)?" grupo "+whereIAm.group:"";
    		var sDate = new Date(reserv.start_date.replace(/-/gi,"/")),stDate=[sDate.getHours().padLeft(),sDate.getMinutes().padLeft()].join(':');
    	    var eDate = new Date(reserv.end_date.replace(/-/gi,"/")),enDate=[eDate.getHours().padLeft(),eDate.getMinutes().padLeft()].join(':');
            var sGroup=(reserv.group)?" grupo "+reserv.group:"";
            var conflict = "La materia " + whereIAm.text +group+" dictada los "+daysOfWeek[whereIAm.day]+" de "+startDate+" a "+endDate+
			" en el sal\u00F3n "+whereIAm.envDTO["description"]+"    >>>    Est\u00E1 en conflicto con "+reserv.text+sGroup+" que se dicta de "+stDate+" a "+enDate; 
            reservConflictDict[key][reserv.id]=conflict;
        }
    }
}


function deleteOnUpdateReservInConlfict(reservId,conflictsResDTO){
	//Borro las reservas que no estan en conflicto tras la actualizacion
	for(key in reservConflictDict){
		if((reservId in reservConflictDict[key])&&!(getInArrayById(conflictsResDTO,key))){//Si no esta en el array es porque no hay mas conflicto con la reserva "key"
			delete reservConflictDict[key][reservId];
		}
	}
}

function initReservInConflict(){
	reservConflictDict={};
}

function getInArrayById(rArray,id){
	var array=new Array(rArray);
	for(var i = 0; i < array[0].length; i++){
		if(array[0][i].id==id){
			return true;
		}
	}
	return false;
}

function deleteReservInConlfict(reservId){
	for(key in reservConflictDict){
		if(reservId in reservConflictDict[key]){
			delete reservConflictDict[key][reservId];
		}
		var countR=0;
		for(var tmpCountR in reservConflictDict[key]){
			countR=tmpCountR;
		    countR=1;
		    break;//Para salir a la primera ocurrencia
		}
		if(countR==0)    
	        delete reservConflictDict[key];
	}
	if(reservConflictDict[reservId])
	    delete reservConflictDict[reservId];
}

function prepareReservConflicts(reserv){
	var array=new Array(reserv.conflictsResDTO);
	var dictReturn = {};
	
	if(array[0].length>0){
		var sDate = new Date(reserv.start_date.replace(/-/gi,"/")),startDate=[sDate.getHours().padLeft(),sDate.getMinutes().padLeft()].join(':');
		var eDate = new Date(reserv.end_date.replace(/-/gi,"/")),endDate=[eDate.getHours().padLeft(),eDate.getMinutes().padLeft()].join(':');
		var group=(reserv.group)?" grupo "+reserv.group:"";
		for(var i = 0; i < array[0].length; i++){
			sDate = new Date(array[0][i].start_date.replace(/-/gi,"/")),stDate=[sDate.getHours().padLeft(),sDate.getMinutes().padLeft()].join(':');
			eDate = new Date(array[0][i].end_date.replace(/-/gi,"/")),enDate=[eDate.getHours().padLeft(),eDate.getMinutes().padLeft()].join(':');
			var sGroup=(array[0][i].group)?" grupo "+array[0][i].group:"";
			var fromYearAndCareer=(scheduler._events[array[0][i].id])?"":" de "+strYear[array[0][i].year]+" a\u00F1o de la carrera "+array[0][i].career;//Si son de la misma planificacion no digo de que a�o y carrera es.
			var conflict = "La materia " + reserv.text +group+" dictada los "+daysOfWeek[reserv.day]+" de "+startDate+" a "+endDate+
			" en el sal\u00F3n "+reserv.rEnvDTO["description"]+"    >>>    Est\u00E1 en conflicto con "+array[0][i].description+sGroup+fromYearAndCareer+" que se dicta de "+stDate+" a "+enDate; 
			dictReturn[array[0][i].id] = conflict;
		}
		return dictReturn;
	}
	return {};
}

function getPlanningByCurrentUser() {	
	$.getJSON('/enma/planning/getByCurrentUser/', function(data) {
			clearPlanningsRepo();
			if(data.responseCode == 200){
				fillCmbCareersFilter(data.careers);
				buildPlannigTable(data);
			}
			setTimeout(function() { 
				hideProgress('loadPlann');	    
		    }, 1000);
			
		});
}

function fillCmbCareersFilter(careers){
	var select = $("#cmbPlannCareerFilter")[0];
    select.options.length = 0; // clear out existing items
    select.options.add(new Option('Todas','ALL'));
	 for(var i=0; i < careers.length; i++) {
		var careerName=careers[i];
	    select.options.add(new Option(careerName, careerName));
	 }
}

function doPlanningFilter() {
	
	var parameters = { 
			"status" : $("#cmbPlannStatusFilter").val(),
			"career" : $("#cmbPlannCareerFilter").val()
			};
	showProgress('loadPlann');
	postJSON("/enma/planning/getByFilterAndCurrentUser/", parameters, function(data) {
		buildPlannigTable(data);
		setTimeout(function() { 
			hideProgress('loadPlann');	    
	    }, 500);
	});
}

function buildPlannigTable(data){
	var currentDiv = $("#contentPlanifications");
	var table = "";
	var tr = "";
	currentDiv.html('');
	
	Number.prototype.padLeft = function(base,chr){
		   var  len = (String(base || 10).length - String(this).length)+1;
		   return len > 0? new Array(len).join(chr || '0')+this : this;
		};
	table+="<table class='table table-hover'><thead><tr><th>Carrera</th><th>A\u00F1o</th><th>Autor</th><th>Per\u00EDodo</th><th>Modificada</th><th>Estado</th><th></th></tr></thead><tbody>";
	
	for(var i = 0; i<data.planningsDTO.length; i++){
		var auxDiv = data.planningsDTO[i];
		getPlanningsRepo()[auxDiv.planningId]=auxDiv;
		period=auxDiv.periodDTO['startDate']+' - '+auxDiv.periodDTO['endDate'];
		tr += "<tr><td>"+auxDiv.career+"</td><td>"+auxDiv.year+"</td><td>"+auxDiv.userName+"</td><td>"+period+"</td><td>"+auxDiv.lastModDate+"</td><td>"+auxDiv.status+"</td><td><input type='radio' name='radioListItem' value='"+auxDiv.planningId+"'></td></tr>";
		}
	table += tr + "</tbody></table>";
    currentDiv.append(table);
}

function goToCalendar() {
		scheduler.myClearAll();
		var career = $("#autocompleteCareer").val();
		var year = $("#selectYear").val();
		if (career != '' && year && defaultPeriod) {
			var planning=new Object();
			planning.career = career;
			planning.year = year;
			planning.periodDTO=getDefaultPeriod();
			//sperez: te mando un json para guardar la planificaci�n
			postJSON("/enma/planning/add/", planning, function(data) {
            	if(data.responseCode==200){
            		currentPlannificationId=data.planningsDTO[0].planningId;
            		getPlanningsRepo()[data.planningsDTO[0].planningId]=data.planningsDTO[0];
            	}
    		});
			setDataProcces(getDataProcessor());
			$("#executeGlobalConlfict").hide();
			$("#confirmReservations").hide();
			$("#conflictPlanification").show();
			$("#configPlanification").show();
			$("#sendPlanification").show();
			setSchedulerNotEditable(false);
			setPlannConfirmed(false);
			
			$("#firstScreen").hide( "fold", {}, 1000);
			$("#calendarTitle").html("Carrera: "+career);
			$("#calendarSubTitle").html("A\u00F1o: "+ getStrYear(parseInt(year)));
			$("#secondScreen").show( "fold", {}, 1000);
			$("#secondScreen").ready(function(){ 
			    setTimeout(function() { 
			    	init();			    
			    }, 2000); 
			});
			var careerYear = new Array(2);
			careerYear[0]=career;
			careerYear[1]=year;
			postJSON("/enma/planning/subjectByCareerAndYear/",careerYear, function(data) {
			availableSignature = new Array(data.subjects.length);

			for ( var i = 0; i < data.subjects.length; i++) {
				availableSignature[i] = String(data.subjects[i].description);
			}

			});
		} else {
			//aca vendria un show error no un alert
			alert("Usted necesita ingresar una carrera, un a\u00F1o y el per\u00edodo para la planificaci\u00F3n.");
		}
}

function goToHistory(){
	
	scheduler.myClearAll();
	var career = $("#autocompleteCareer").val();
	var year = $("#selectYear").val();
	if (career != '' && year != '' && getDefaultPeriod()!='') {
		$("#closeHistorybutton").show();
		$("#confirmCareerAndYear").hide();
		var planning=new Object();
		planning.career = career;
		planning.year = year;
		planning.periodDTO=getDefaultPeriod();
		showProgress('loadPlann');
		var carAndYear={"career":career,"year":year};
		postJSON("/enma/planning/history/get", carAndYear, function(data) {
			if(data.responseCode == 200){			
				hideProgress('loadPlann');				
				
				var currentDiv = $("#contentHistoryPlanifications");
				var table = "";
				var tr = "";
				currentDiv.html('');				
				
				table+="<table class='table table-hover'><thead><tr><th>Carrera</th><th>A\u00F1o</th><th>Autor</th><th>Per\u00EDodo</th><th>Modificada</th><th>Estado</th><th></th></tr></thead><tbody>";
				
				
				if(data.responseCode == 200){
					for(var i = 0; i<data.planningsDTO.length; i++){
						var auxDiv = data.planningsDTO[i];
						getPlanningsRepo()[auxDiv.planningId]=auxDiv;
						period=auxDiv.periodDTO['startDate']+' - '+auxDiv.periodDTO['endDate'];
						tr += "<tr><td>"+auxDiv.career+"</td><td>"+auxDiv.year+"</td><td>"+auxDiv.userName+"</td><td>"+period+"</td><td>"+auxDiv.lastModDate+"</td><td>"+auxDiv.status+"</td><td><input type='radio' name='radioListItemH' value='"+auxDiv.planningId+"'></td></tr>";
						}
					table += tr + "</tbody></table>";
		            currentDiv.append(table);
		            currentDiv.show();
				}
				$("#historyCareerAndYear").hide();
				$("#loadHistoryCareerAndYear").show();
				setTimeout(function() { 
					hideProgress('loadPlann');	    
			    }, 1000);								
			}else{
				hideProgress('loadPlann');
				alert(data.message);
			}
		});
	} else {
		//aca vendria un show error no un alert
		//alert("Usted necesita ingresar una carrera, un a\u00F1o y el periodo para la planificaci\u00F3n actual");
		$("#dialogHome2").dialog();
	}
}

function planningFromHistory(){
	var selected = $("input[type='radio'][name='radioListItemH']:checked");
	if (selected.length > 0){
		showProgress('load');
		var plannId = selected.val().toString();
		var plannPeriod={"plann":{"id":plannId},"period":getDefaultPeriod()};
		postJSON("/enma/planning/history/add", plannPeriod, function(data) {
        	if(data.responseCode==200){
        		$("#historyCareerAndYear").hide();
        		$("#loadHistoryCareerAndYear").show();
        		$("#contentHistoryPlanifications").hide();
        		var historyPlann = data.planningsDTO[0];
        		currentPlannificationId=historyPlann.planningId;
        		getPlanningsRepo()[historyPlann.planningId]=historyPlann;
        		initReservInConflict();
        		setPlannConfirmed(false);
        		goToPlanning(parseInt(currentPlannificationId),getDataProcessor());
        	}
		});
	} else {
		$("#selectOpenPlanificationDialog").dialog();
	}
}

function cleanInputsCareerAndyear(){
	$("#autocompleteCareer").val('');
}

function returnFromCalendar() {
		if (configPanelIsOpen) {
			$("#configPanel").hide("slide", {}, 1000);
			$("#scheduler_planning").show("slide", {}, 1000, function(){
				scrollBarWasSetting = false;
				setScrollBarPosition(null);
			});
			configPanelIsOpen = false;
		} else if(conflictPanelIsOpen){
			$("#conflictPanel").hide("slide", {}, 1000);
			$("#scheduler_planning").show("slide", {}, function(){
				scrollBarWasSetting = false;
				setScrollBarPosition(null);
			});
			conflictPanelIsOpen = false;
		} else {			
			showProgress('loadPlann');
			$("#secondScreen").hide( "fold", {}, 1000);
			$("#firstScreen").show( "fold", {}, 1000);
			newPlanification(false);
			doPlanningFilter();
			scheduler._lightbox=null;
			if(viewPlanningRecived){
				showProgress('loadPlann');
				getSendedPlanifiaction();
			}
		}
		plannIsOpen = false;
	}

function closeSelectRoomPlanification() {
	var roomPopUp = $("#roomPopUp");
	roomPopUp.hide("slide", {}, 1000);
	$("#filterSelectDay").hide();
	$("#filterShift").hide();
	$("#filterStartDay").show();
	$("#filterEndDay").show();
}

function createSignatureAutocomplete(id) {
	// availableSignature se completa al saber la carrera y el a�o
	if(getWhereAmI()==1){
		$(id).autocomplete({
			source : availableSignature
		});
	}

}

function dataInitialize() {
	if (confirm('Esta seguro? La base de datos se inicializar\u00E1'))
		postJSON("/enma/home/admin_services/initialize/", '', function(data) {
			if (data)
				$("#dialogHome3").dialog();
			else
				$("#dialogHome4").dialog();
		});

}

function openConfigPanel() {
		if(!configPanelIsOpen) {
			configPanelIsOpen = true;
			$("#periodSelectedConfigPanel").html("<h3 style='color:#576365;'>"+periodSelectedConfigPanel+"</h3>");
			//Creo el autocomplete para las materias en el panel de configuraci�n.
			if(!getSchedulerNotEditable()){
				$("#addSpecialPeriod").show();
				createSignatureAutocomplete("#autocompleteSignaturePanelConfig");
				$("#panelConfigStartDay").datepicker();
				$("#panelConfigEndDay").datepicker();
				$("#panelConfigSignatureStartDay").datepicker();
				$("#panelConfigSignatureEndDay").datepicker();
			}else{
				$("#addSpecialPeriod").hide();
			}
			if(conflictPanelIsOpen){
				$("#conflictPanel").hide("slide", {}, 1000);
				conflictPanelIsOpen = false;
			} else {
				$("#scheduler_planning").hide("slide", {}, 1000);
			}
			$("#configPanel").show("slide", {}, 1000);
		}
	}

function openConflictPanel(){
	if(!conflictPanelIsOpen) {
		conflictPanelIsOpen = true;		
		if(configPanelIsOpen){
			$("#configPanel").hide("slide", {}, 1000);
			configPanelIsOpen = false;
		} else {
			$("#scheduler_planning").hide("slide", {}, 1000);
		}
		$("#conflictPanel").show("slide", {}, 1000);
		$("#conflictPanelContent").html('');
		var idArrayAux=[];//Para no mostrar conflictos repetidos
		cant = 1;
		for(var i in reservConflictDict){
			for(var j in reservConflictDict[i]){
				if(idArrayAux.indexOf(i+"#"+j)==-1&&idArrayAux.indexOf(j+"#"+i)==-1){
				    $("#conflictPanelContent").append("<div class='alert alert-error'><h4>Conflicto #"+(cant)+"</h4>"+reservConflictDict[i][j]+"</div>");
				    cant++;
				}
			    idArrayAux.push(i+"#"+j);
			    idArrayAux.push(j+"#"+i);
			}			
		}
	}
}

function sendPlanning() {
	if(getPlanningsRepo()[currentPlannificationId].status=='Esperando confirmaci�n'||getPlanningsRepo()[currentPlannificationId].status=='Esperando confirmaci\u00F3n'){
		//alert("La planificaci\u00F3n ya ha sido enviada");
		$("#dialogHome5").dialog();
	}else{
		$("#sendPlanificationDialog").dialog();
	}
	
}

function confirmPlanning() {
	if(getPlanningsRepo()[currentPlannificationId].status=='Confirmada'){
		//alert("La planificaci\u00F3n ya ha sido confirmada");
		$("#dialogHome6").dialog();
	}else{
		$("#confirmReservationDialog").dialog();
	}
	
}

function isEmpty(map) {
   for(var key in map) {
      if (map.hasOwnProperty(key)) {
         return false;
      }
   }
   return true;
}

function sendPlanificationPhaseTwo(){
	//sperez: servicio para enviar la notificaci�n.
	$("#sendPlanificationDialog").dialog("close");
	if(!isEmpty(reservConflictDict)){
		//alert("La planificaci\u00F3n tiene conflictos locales, la misma no puede ser enviada hasta que se resuelvan.");
		$("#dialogHome7").dialog();
	}else{
		postJSON("/enma/planning/send", currentPlannificationId, function(data) {
        	if(data.responseCode==200){
        		var sendedPlann = data.planningsDTO[0];
        		currentPlannificationId=sendedPlann.planningId;
        		getPlanningsRepo()[sendedPlann.planningId]=sendedPlann;
        		initReservInConflict();
        		goAfterSend(parseInt(currentPlannificationId));
        	}else{
        		alert(data.message);
        	}
		});
	}
	
}

function confirmReservationsPhaseTwo(){
	$("#confirmReservationDialog").dialog("close");
	if(!isEmpty(reservConflictDict)){
		//alert("La planificaci\u00F3n tiene conflictos, las reservas no pueden ser confirmadas hasta que se resuelvan.");
		$("#dialogHome8").dialog();
	}else{
		
		postJSON("/enma/planning/confirm", currentPlannificationId, function(data) {
        	if(data.responseCode==200||data.responseCode==506){
        		var confirmedPlann = data.planningsDTO[0];
        		currentPlannificationId=confirmedPlann.planningId;
        		initReservInConflict();
        		getPlanningsRepo()[confirmedPlann.planningId]=confirmedPlann;
        	}
        	if(data.responseCode==200){
        		goAfterConfirmed(parseInt(currentPlannificationId));
        	}else{
        		if(data.responseCode==506){
        			goAfterVerifyGlobalConflict(parseInt(currentPlannificationId));
        			hideProgress('proc');
        			$("#dialogHome8").dialog();
        		}
        	}
		});
	}
	
}

function preInitReservation(){
	setSchedulerNotEditable(false);
	scheduler.myClearAll();
	showProgress('load');
}

function initReservation() {
	if (iAmIn==2) {
		preInitReservation();
		setTimeout(function() {
			if(!getDataProcessor()){
				var dataP = new dataProcessor("");
				dataP.init(scheduler);
				setDataProcessor(dataP);
			}
			
		initDailyResDatePickers();
		$.getJSON('/enma/planning/daily/getByCurrentUser/', function(data) {
			if(data.responseCode == 200){
				setDailysRepo(data.dReservations);
				goToDaily(getDataProcessor());
			}
			hideProgress('load');
		});
		}, 2000);
	}
}

function initDailyResDatePickers(){
	$("#resStartDayPeriod").datepicker({
        onSelect: function (date) {
            var dt2 = $('#resEndDayPeriod');
            var minDate = $(this).datepicker('getDate');
            
            dt2.datepicker('option', 'minDate', minDate);
            dt2.datepicker('setDate', minDate);
            
        }
    });
    $('#resEndDayPeriod').datepicker();
}

function loadDailyReservationPeriod(){	
	var period = new Object();
	period.type="1";
	period.startDate = $('#resStartDayPeriod').val();
	period.endDate = $('#resEndDayPeriod').val();
	period.desciption="";
	
	if(period.startDate=="" || period.endDate==""){
		alert("Debe llenar los dos campos de fecha.");
	}else{

		preInitReservation();
		setTimeout(function() {
			if(!getDataProcessor()){
				var dataP = new dataProcessor("");
				dataP.init(scheduler);
				setDataProcessor(dataP);
			}
			postJSON("/enma/planning/daily/getByCurrentUserByDate", period, function(data) {
				if(data.responseCode==200){
					setDailysRepo(data.dReservations);
					goToDaily(getDataProcessor());
				}
				hideProgress('load');
			});
		}, 100);
		
	}
}

function initReservationsByEnv() {
	if (iAmIn==5) {
		fillReservByEnvCombo();
		setSchedulerNotEditable(true);
		scheduler.myClearAll();
		if(!getDataProcessor()){
			var dataP = new dataProcessor("");
			dataP.init(scheduler);
			setDataProcessor(dataP);
			pInit();
		}
	}
}

function getReservationByEnv(){
	var envi=$("#priorityRoomNameResByEnv").val();
	showProgress('load');
	setTimeout(function() {
		if(!getDataProcessor()){
			var dataP = new dataProcessor("");
			dataP.init(scheduler);
			setDataProcessor(dataP);
		}
	
	postJSON('/enma/planning/reservationsByEnv/',envi, function(data) {
		if(data.responseCode == 200){
			setDailysRepo(data.dReservations);
			goToDaily(getDataProcessor());
		}
		hideProgress('load');
	});
	}, 2000);
}

function initPlanning() {
	if (iAmIn==1) {
		if(!getDataProcessor()){
			var dp = new dataProcessor("");
			dp.init(scheduler);
			setDataProcessor(dp);
		}
		if(plannIsOpen){
			returnFromCalendar();
		}else{
			showProgress('loadPlann');
			newPlanification(false);
			getPlanningByCurrentUser();
			scheduler._lightbox=null;
			if(viewPlanningRecived){
				showProgress('loadPlann');
				getSendedPlanifiaction();
			}
		}
	}
}


function fillReservByEnvCombo(){
	//obtengo los salones
	$.getJSON("/enma/home/environment/", function(data) {
		var salon = [];
		
		for (var i in data.environmentDTOs) {
			salon[i] = { id: data.environmentDTOs[i].id, value: data.environmentDTOs[i].description };
		}

	    var select = $("#priorityRoomNameResByEnv")[0];
	    select.options.length = 0; // clear out existing items
	    select.options.add(new Option('',''));
	    for(var i=0; i < salon.length; i++) {
	        var d = salon[i];
	        select.options.add(new Option(d.value, d.id));
	    }
	   
	});
}

function getCurrentPlannId(){
	return parseInt(currentPlannificationId);
}


$(function() {
	$("#tabs").tabs();
	postJSON("/enma/planning/careerAndYear/", '', function(data) {
		var availableTags = new Array(data.careers.length);

		for ( var i = 0; i < data.careers.length; i++) {
			availableTags[i] = String(data.careers[i]);
		}
		$("#autocompleteCareer").autocomplete({
			source : availableTags
		});

//		var availableYear = new Array(data.maxYear);
		var years = [];
		
		for ( var i = 0; i < data.maxYear; i++) {
			var strY=String((i + 1));
			years[i] = { text: strY, value: strY };
		}

        var select = $("#selectYear")[0];
        select.options.length = 0; // clear out existing items
        select.options.add(new Option('',''));
        for(var i=0; i < years.length; i++) {
            var d = years[i];
            select.options.add(new Option(d.text, d.value));
        }

	});

	// run the currently selected effect
	function runEffect() {
		// get effect type from
		var selectedEffect = "fold";

		// run the effect
		$("#effect").hide(selectedEffect, {}, 1000, callback);
	}
	;

	// callback function to bring a hidden box back
	function callback() {
		var selectedEffect = "fold";

		// run the effect
		$("#effect1").show(selectedEffect, {}, 500, callback);
	}
	;

	// set effect from select menu value
	$("#button").click(
			function() {
				if ($("#autocompleteCareer").val() != ''
						&& $("#selectYear").val() != '') {
					runEffect();
					return false;
				} else {
					//alert("Debe completar los datos");
					$("#dialogHome9").dialog();
				}
			});

	$("#effect1").hide();
	$("#effect2").hide();

	$("#dialog").dialog({
		autoOpen : false,
		width : 400,
		buttons : [ {
			text : "Ok",
			click : function() {
				$(this).dialog("close");
			}
		}, {
			text : "Cancel",
			click : function() {
				$(this).dialog("close");
			}
		} ]
	});
});

function createSignature() {
	if ($("#autocompleteSignature").val() != '') {
		var currentButton = $('<input>', {
			id : 'signature',
			type : 'button',
			value : $("#autocompleteSignature").val(),
			click : function() {
				$("#confirmSignature").attr('disabled', true);
				$("#effect2").show('slide', {}, 500, null);
			}
		})
		$('#effect1').append(currentButton);
		$("#autocompleteSignature").val('');
	} else {
		//alert("Debe ingresar una materia");
		$("#dialogHome10").dialog();
	}
}

function closeSignatureOptions() {

	$('input[name=lunes]').attr('checked', false);
	$("#effectLunes").hide('blind', {}, 1000, null);

	$('input[name=martes]').attr('checked', false);
	$("#effectMartes").hide('blind', {}, 500, null);

	$('input[name=miercoles]').attr('checked', false);
	$("#effectMiercoles").hide('blind', {}, 500, null);

	$('input[name=jueves]').attr('checked', false);
	$("#effectJueves").hide('blind', {}, 500, null);

	$('input[name=viernes]').attr('checked', false);
	$("#effectViernes").hide('blind', {}, 500, null);

	$('input[name=sabado]').attr('checked', false);
	$("#effectSabado").hide('blind', {}, 500, null);

	$("#effect2").hide('slide', {}, 500, null);
	$("#confirmSignature").attr('disabled', false);
}

function setTimes(day) {
	switch (day) {
	case "lunes":
		$("#effectLunes").show('blind', {}, 500, null);
		break;
	case "martes":
		$("#effectMartes").show('blind', {}, 500, null);
		break;
	case "miercoles":
		$("#effectMiercoles").show('blind', {}, 500, null);
		break;
	case "jueves":
		$("#effectJueves").show('blind', {}, 500, null);
		break;
	case "viernes":
		$("#effectViernes").show('blind', {}, 500, null);
		break;
	case "sabado":
		$("#effectSabado").show('blind', {}, 500, null);
		break;
	default:
		null;
	}
}

function whereAmI(tab){
	iAmIn = tab;
	if(iAmIn == 6){
		loadHelpPDF();
	}else if(iAmIn == 2){
		$('#resStartDayPeriod').val("");
		$('#resEndDayPeriod').val("");
	}
}

function lockControl(){
	$.getJSON('/enma/period/lockControl/', function(data) {
		if(data.responseCode == 200){
			initReservation();
		}else{
			alert("Per\u00edodo de planificaci\u00f3n en progreso, momentaneamente no se pueden realizar reservas. Por consultas dirigirse al administrador.");
		}
			
	});	
}

function autoResize(){
    var newheight;
    var newwidth;
    var id = 'adminFrame';

    if(document.getElementById){
        newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
        newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
    }

    document.getElementById(id).height= (newheight) + "px";
    document.getElementById(id).width= (newwidth) + "px";
}

function getWhereAmI(){
	return iAmIn;
}

function showAddPeriod(){
	$("#addNewPeriod").show('clip',{},1000,null);
	$("#addnewPeriodShowButton").hide();
	$("#addnewPeriodHideButton").show();
}
function hideAddPeriod(){
	$("#addNewPeriod").hide('clip',{},1000,null);
	$("#addnewPeriodHideButton").hide();
	$("#addnewPeriodShowButton").show();
}